package com.atguigu.gmall.common.config.exception.handler;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理
 * 异常切面
 */
@RestControllerAdvice  //aop advice通知

public class GlobalExceptionHandler {
    /**
     * 处理所有controller 其他 异常
     * 返回的是一个json
     */
    @ExceptionHandler(Exception.class)
    public Result HandException(Exception e){
        Result<Object> fail = Result.fail();
        fail.setMessage(e.getMessage());
        return  fail;

    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException exception){

        //1、从这个异常中拿到校验结果
        BindingResult bindingResult = exception.getBindingResult();
        //2、把结果整理下返回前端：  {tel:"",consignee:""}
        Map<String,String> errMap = new HashMap<>();
        for (FieldError error : bindingResult.getFieldErrors()) {
            String field = error.getField(); //错误发生的属性
            String message = error.getDefaultMessage(); //错误消息
            errMap.put(field,message);
        }
        return Result.build(errMap, ResultCodeEnum.INVAILD_PARAM);
    }

    /**
     * 业务有关的异常
     * @param e
     * @return
     */
    @ExceptionHandler(GmallException.class)
    public Result HandGmallException(GmallException e){
        Result<Object> fail = Result.fail();
        fail.setCode(e.getCode());
        fail.setMessage(e.getMessage());
        return  fail;

    }

}
